const express = require("express");
const jsonServer = require("json-server");
const bodyParser = require("body-parser");

const app = express();
const PORT = 3000;

// Middleware for parsing JSON
app.use(bodyParser.json());

// Whitelist routes that bypass authentication
const whitelist = [
  "/login",
  "/public",
  "/api/posts",
  "/api/users",
  "/api/db1",
  "/api/db2",
  "/api/main/users",
];

// Authentication middleware
app.use((req: any, res: any, next: any) => {
  if (whitelist.some((route) => req.path.startsWith(route))) {
    return next();
  }

  const token = req.headers.authorization;
  if (!token || token !== "mock-token") {
    return res.status(401).json({ message: "Unauthorized" });
  }

  next();
});

// Custom routes
app.get("/custom", (req: any, res: any) => {
  res.json({ message: "This is a custom route" });
});

// JSON Server setup for multiple JSON files
const mainRouter = jsonServer.router("db.json");
app.use("/api/user", mainRouter);
const db1Router = jsonServer.router("db1.json");
const db2Router = jsonServer.router("db2.json");
app.use("/api/blog", db1Router);
app.use("/api/db2", db2Router);

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});
